package com.gmail.viktor.yuryev.ui;

import com.gmail.viktor.yuryev.model.Link;
import com.gmail.viktor.yuryev.model.ServerDetails;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.options.BaseConfigurable;
import com.intellij.ui.*;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.JBTextField;
import com.intellij.ui.table.JBTable;
import com.intellij.util.Consumer;
import com.intellij.util.ui.ColumnInfo;
import com.intellij.util.ui.ListTableModel;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import java.awt.*;
import java.nio.file.Path;
import java.util.ArrayList;

/**
 * Created by Viktor Yuryev on 4/9/2014.
 */
public class ServerConfigurationForm extends BaseConfigurable {
    private final ListTableModel<Link> myModel;
    private JBTextField serverTextField;
    private JPanel rootComponent;
    private JBLabel serverLabel;
    private JBLabel loginLabel;
    private JBLabel portLabel;
    private JPasswordField passwordField;
    private JBLabel passwordLabel;
    private JBTextField loginTextField;
    private JBTextField portTextField;
    private JBTable tableFolderMapping;
    private JPanel panelFolders;

    private ServerDetails data;
    private final Consumer<ServerDetails> changeListener;


    private final ColumnInfo<Link, String> LOCAL_COLUMN = new ColumnInfo<Link, String>("Local"/*VcsBundle.message("issue.link.issue.column")*/) {
        public String valueOf(Link link) {
            Path localFolder = link.getLocalFolder();
            return localFolder == null ? null : localFolder.toString();
        }

        @Override
        public void setValue(Link link, String value) {
            link.setLocalFolder(value);
        }

        @Override
        public boolean isCellEditable(Link link) {
            return true;
        }
    };
    private final ColumnInfo<Link, String> REMOTE_COLUMN = new ColumnInfo<Link, String>("Remote"/*VcsBundle.message("issue.link.link.column")*/) {
        public String valueOf(Link link) {
            Path remoteFolder = link.getRemoteFolder();
            return remoteFolder == null ? null : remoteFolder.toString();
        }

        @Override
        public boolean isCellEditable(Link link) {
            return true;
        }

        @Override
        public void setValue(Link link, String value) {
            link.setRemoteFolder(value);
        }
    };
    private ArrayList<Link> myLinks;


    public ServerConfigurationForm(Consumer<ServerDetails> changeListener) {
        this.changeListener = changeListener;
        serverLabel.setLabelFor(serverTextField);
        loginLabel.setLabelFor(loginTextField);
        passwordLabel.setLabelFor(passwordField);
        portLabel.setLabelFor(portTextField);
        installListener(portTextField);

        ToolbarDecorator toolbar = ToolbarDecorator.createDecorator(tableFolderMapping);

        toolbar.setAddAction(new AnActionButtonRunnable() {
            @Override
            public void run(AnActionButton anActionButton) {
                Link item = new Link("/", "/");
              //  myModel.addRow(item);
                myLinks.add(item);
            }
        });
        toolbar.setRemoveAction(new AnActionButtonRunnable() {
            @Override
            public void run(AnActionButton anActionButton) {
                int selectedRow = tableFolderMapping.getSelectedRow();
                //myModel.removeRow(selectedRow);
                myLinks.remove(selectedRow);
            }
        });


        myLinks = new ArrayList<Link>();
      /*  for(IssueNavigationLink link: configuration.getLinks()) {
            myLinks.add(new IssueNavigationLink(link.getIssueRegexp(), link.getLinkRegexp()));
        }*/
        myModel = new ListTableModel<Link>(
                new ColumnInfo[]{LOCAL_COLUMN, REMOTE_COLUMN},
                myLinks,
                0);
        tableFolderMapping.setModel(myModel);
        panelFolders.add(toolbar.createPanel(), BorderLayout.CENTER);

    }


    protected void installListener(JTextField textField) {
        textField.getDocument().addDocumentListener(new DocumentAdapter() {
            @Override
            protected void textChanged(DocumentEvent e) {
                ApplicationManager.getApplication().invokeLater(new Runnable() {
                    public void run() {
                        apply();
                    }
                });
            }
        });
    }


    public JComponent getRootComponent() {
        return rootComponent;
    }

    public void setData(ServerDetails data) {
        this.data = data;
        serverTextField.setText(data.getHost());
        loginTextField.setText(data.getLogin());
        portTextField.setText(String.valueOf(data.getPort()));
        passwordField.setText(data.getPassword());
        myLinks.clear();
        for (Link link : data.getMapping()) {
            myLinks.add(link.clone());
        }

        myModel.setItems(myLinks);
        myModel.fireTableDataChanged();

    }


    @Override
    public boolean isModified() {
        return true;
    }

    public boolean isModified(ServerDetails data) {
        if (serverTextField.getText() != null ? !serverTextField.getText().equals(data.getHost()) : data.getHost() != null)
            return true;
        if (loginTextField.getText() != null ? !loginTextField.getText().equals(data.getLogin()) : data.getLogin() != null)
            return true;
        if (String.valueOf(data.getPort()).equals(portTextField.getText()))
            return true;
        if (passwordField.getText() != null ? !passwordField.getText().equals(data.getPassword()) : data.getPassword() != null)
            return true;
        return false;
    }


    @Nls
    @Override
    public String getDisplayName() {
        return "servers";
    }

    @Nullable
    @Override
    public String getHelpTopic() {
        return null;
    }

    @Nullable
    @Override
    public JComponent createComponent() {
        return rootComponent;
    }

    @Override
    public void apply() {
        data.setHost(serverTextField.getText());
        data.setLogin(loginTextField.getText());
        data.setPort(Integer.valueOf(portTextField.getText()));
        data.setPassword(passwordField.getText());
        data.setMapping(myLinks);
        changeListener.consume(data);
    }

    @Override
    public void reset() {
        System.out.println("reset was invoked");
    }

    @Override
    public void disposeUIResources() {

    }

}
